<script setup lang="ts">

import { computed, onMounted } from 'vue';
import { useStore } from 'vuex';

const store = useStore();

// 页面加载时检查 sessionStorage 是否有存储的用户信息
// useStore当页面刷新会丢失，每当刷新就重新从session里取出并为其赋值，useStore可在整个vue里共享
const savedUserInfoStr = sessionStorage.getItem('userInfo');
if (savedUserInfoStr) {
  try {
    const userInfo = JSON.parse(savedUserInfoStr);
    store.dispatch('setUserInfo', userInfo);
  } catch (err) {
    console.error('解析 userInfo 出错', err);
  }
}

// 通过 computed 计算出展示数据
const username = computed(() => store.state.username || '未登录');
const avatar = computed(() => store.state.avatar ? `data:image/png;base64,${store.state.avatar}` : '');


</script>


<template>
  <div id="app">
    <nav>
      <router-link to="/">首页</router-link>
      <router-link to="/resources">列表</router-link>
      <router-link to="/upload">上传</router-link>
      <router-link to="/manage">管理</router-link>
      <router-link to="/profile">个人</router-link>
      <router-link to="/login">登陆</router-link>
    </nav>
    <router-view />
  </div>

  <h2>{{ username }}</h2>
  <!-- 判断 avatar 是否存在 -->
  <img v-if="avatar" :src="avatar" alt="头像" />
</template>

<style scoped></style>